import { defineStore } from "pinia"
import { computed, ref } from "vue"
import { useMenuStore } from '@/store/menu.js'
import { logout as logoutApi } from '@/api/system/sysUser.js'

//用户Token
export const useAdminUserStore = defineStore('adminUser', () => {
    const token = ref(null)
    const tokenCacheKey = "cb-token";

    const tokenInfo = computed(() => {
        return getToken()
    })

    function getToken() {
        const cacheTokenData = sessionStorage.getItem(tokenCacheKey)
        token.value = null
        if (cacheTokenData) {
            token.value = JSON.parse(cacheTokenData)
        }
        return token.value
    }

    function setToken(tokenData) {
        token.value = tokenData
        sessionStorage.setItem(tokenCacheKey, JSON.stringify(tokenData))
    }

    function clearToken() {
        token.value = null
        sessionStorage.removeItem(tokenCacheKey)
    }

    //注销登陆
    const logout = async () => {
        await logoutApi()

        //清空TOKEN
        clearToken()

        //初始化菜单相关状态
        const menuStore = useMenuStore()
        menuStore.destroy()
    }

    return {token, setToken, tokenInfo, clearToken, logout}
})
